<template>
  <Row>
    <Col span="23" offset="1">
      <h2>可视化网站资源库</h2>
      <div style="display: flex; position: absolute; top: -20px; right: 70px">
        <Button
          class="add-btn"
          type="warning"
          @click="addItemModalShow()"
          icon="ios-create"
          style="margin-right: 20px"
          v-show="userInfo.role == 'admin'"
          >快速添加</Button
        >
        <Input
          v-model="inputSearchText"
          placeholder="请输入内容"
          class="project-input"
          clearable
          @keyup.enter.native="search"
          @on-clear="readResource"
        >
          <Select v-model="searchTag" slot="prepend" style="width: 80px; height: 32px">
            <Option label="名称" value="name">名称</Option>
            <Option label="描述" value="description">描述</Option>
            <Option label="网址" value="url">网址</Option>
          </Select>
        </Input>
        <Button
          slot="append"
          icon="ios-search"
          class="search-btn"
          type="primary"
          @click="search"
          >搜索</Button
        >
      </div>

      <div class="main" :style="{ height: contentHeight }">
        <div class="resourcePanel">
          <div class="resourcePanel" style="margin-top: 5px">
            <Row style="height: 100%; overflow-y: auto">
              <template>
                <Col span="23" offset="0">
                  <div class="literature_container page-callrecords">
                    <div class="page-content" ref="pageTab">
                      <div class="page-tab">
                        <el-table
                          :data="tableData"
                          style="width: 100%"
                          border
                          :header-cell-style="{ background: '#00abbe', color: '#fff' }"
                        >
                          <el-table-column
                            prop="tempId"
                            label="#"
                            width="50"
                            align="center"
                          ></el-table-column>
                          <el-table-column
                            align="center"
                            prop="name"
                            min-width="100"
                            label="网站名称"
                          >
                            <template slot-scope="scope">
                              <p
                                style="
                                  overflow: hidden;
                                  white-space: nowrap;
                                  text-overflow: ellipsis;
                                "
                                :title="scope.row.name"
                              >
                                {{ scope.row.name }}
                              </p>
                            </template>
                          </el-table-column>
                          <el-table-column
                            align="center"
                            prop="description"
                            min-width="170"
                            label="描述"
                          >
                            <template slot-scope="scope">
                              <p
                                style="
                                  overflow: hidden;
                                  white-space: nowrap;
                                  text-overflow: ellipsis;
                                "
                                :title="scope.row.description"
                              >
                                {{ scope.row.description }}
                              </p>
                            </template>
                          </el-table-column>
                          <el-table-column
                            align="center"
                            prop="url"
                            min-width="170"
                            label="网址"
                          >
                            <template slot-scope="scope">
                              <a
                                style="
                                  text-decoration: underline;
                                  width: 150px;
                                  overflow: hidden;
                                  white-space: nowrap;
                                  text-overflow: ellipsis;
                                "
                                @click="copyUrl(scope.row)"
                                >{{ scope.row.url }}</a
                              >
                            </template>
                          </el-table-column>
                          <!-- <el-table-column align="center" prop="date" width="226" min-width="100" label="时间"></el-table-column> -->
                          <!-- <el-table-column align="center" prop="classification" label="类别"></el-table-column> -->
                          <el-table-column align="center" label="操作" width="150">
                            <template slot-scope="scope">
                              <!-- size="small" -->
                              <el-button
                                size="mini"
                                class="operation-btn"
                                round
                                type="info"
                                @click="enterUrl(scope.row)"
                                >查看</el-button
                              >
                              <el-button
                                size="mini"
                                class="operation-btn"
                                round
                                type="warning"
                                @click="handleEdit(scope.row)"
                                v-show="userInfo.role == 'admin'"
                                >编辑</el-button
                              >
                            </template>
                          </el-table-column>
                        </el-table>
                      </div>
                    </div>
                  </div>
                </Col>
              </template>
            </Row>
          </div>

          <div style="display: flex; justify-content: center; margin-top: 25px">
            <Page
              :total="dataCount"
              :page-size="pageSize"
              :current="currentPage"
              show-total
              @on-change="changepage"
              show-elevator
            />
          </div>
          <a class="target" href="" target="_blank" ref="target"></a>
        </div>
      </div>
    </Col>
    <Modal
      v-model="addItemModal"
      title="添加可视化网站条目"
      @on-ok="submitFile()"
      ok-text="添加"
      cancel-text="取消"
      :mask-closable="false"
      width="600px"
    >
      <div style="display: flex; align-items: center; justify-content: center">
        <!-- 这里定义上传的几种资源类型供用户选择 -->
        <span style="width: 20%; text-align: center">上传类型： </span>
        <RadioGroup v-model="addOperationType" style="width: 70%; float: left">
          <Radio label="single">单条目添加</Radio>
          <Radio label="multi">多条目添加</Radio>
        </RadioGroup>
        <!-- 结束 -->
      </div>
      <div
        style="
          display: flex;
          align-items: center;
          justify-content: center;
          margin-top: 20px;
        "
        v-if="addOperationType == 'single'"
      >
        <span style="width: 20%; text-align: center">网站名称：</span>
        <Input type="text" v-model="fileName" style="width: 70%; float: left" />
      </div>
      <div
        style="
          display: flex;
          align-items: center;
          justify-content: center;
          margin-top: 10px;
        "
        v-if="addOperationType == 'single'"
      >
        <span style="width: 20%; text-align: center">网址：</span>
        <Input type="text" v-model="fileURL" style="width: 70%; float: left" />
      </div>
      <div
        style="
          display: flex;
          align-items: center;
          justify-content: center;
          margin-top: 10px;
        "
        v-if="addOperationType == 'single'"
      >
        <span style="width: 20%; text-align: center">描述：</span>
        <Input
          type="textarea"
          :rows="3"
          v-model="fileDescription"
          style="width: 70%; float: left"
        />
      </div>
      <!-- <div style="display:flex;align-items:center;justify-content:center;margin-top:10px;" v-if="addOperationType == 'single'">
        <span style="width:20%; text-align:center;">类型：</span>
        <Input type="text" v-model="fileType" style="width:70%; float:left;"/>
      </div> -->
      <Upload
        :max-size="1024 * 1024"
        v-if="addOperationType == 'multi'"
        type="drag"
        :before-upload="gatherFile"
        action="-"
        style="margin-top: 20px; margin-left: 10%; width: 80%"
      >
        <div style="padding: 20px 0">
          <Icon type="ios-cloud-upload" size="52" style="color: #3399ff"></Icon>
          <p>
            点击或拖拽文件上传 ( 文件大小不超过
            <span style="color: red">2GB</span>)
          </p>
        </div>
      </Upload>
      <div style="padding: 0 10px 0 10px; max-height: 200px; overflow-y: auto">
        <ul v-for="(list, index) in toUploadFiles" :key="index">
          <li style="display: flex">
            File name:
            <span style="font-size: 10px; margin: 0 5px 0 5px"
              >{{ list.name }} ( {{ list.fileSize }} )</span
            >
            <Icon
              type="ios-close"
              size="20"
              @click="delFileList(index)"
              style="display: flex; justify-content: flex-end; cursor: pointer"
            ></Icon>
          </li>
        </ul>
      </div>
      <Alert
        show-icon
        v-if="addOperationType == 'multi'"
        style="margin-top: 5px; margin-left: 10%; width: 80%"
        closable
      >
        提示
        <Icon type="ios-bulb-outline" slot="icon"></Icon>
        <template slot="desc">该功能正在测试中，敬请期待。 </template>
      </Alert>
    </Modal>
    <Modal
      v-model="editModal"
      title="编辑可视化网站条目"
      :mask-closable="false"
      width="600px"
    >
      <div
        style="
          display: flex;
          align-items: center;
          justify-content: center;
          margin-top: 10px;
        "
      >
        <span style="width: 20%; text-align: center">网站名称：</span>
        <Input type="text" v-model="editItemForm.name" style="width: 70%; float: left" />
      </div>
      <div
        style="
          display: flex;
          align-items: center;
          justify-content: center;
          margin-top: 10px;
        "
      >
        <span style="width: 20%; text-align: center">网址：</span>
        <Input type="text" v-model="editItemForm.url" style="width: 70%; float: left" />
      </div>
      <div
        style="
          display: flex;
          align-items: center;
          justify-content: center;
          margin-top: 10px;
        "
      >
        <span style="width: 20%; text-align: center">描述：</span>
        <Input
          type="textarea"
          :rows="3"
          v-model="editItemForm.description"
          style="width: 70%; float: left"
        />
      </div>
      <!-- <div style="display:flex;align-items:center;justify-content:center;margin-top:10px;">
        <span style="width:20%; text-align:center;">类型：</span>
        <Input type="text" v-model="fileType" style="width:70%; float:left;"/>
      </div> -->
      <div slot="footer">
        <Button
          type="error"
          style="float: left"
          icon="ios-remove-circle-outline"
          @click="deleteItem()"
          >删除</Button
        >
        <Button @click="editModal = false">取消</Button>
        <Button type="primary" @click="submitEdit()">确定修改</Button>
      </div>
    </Modal>
  </Row>
</template>

<script>
import { get, post, del, put } from "@/axios";

export default {
  name: "websiteResource",
  watch: {},
  data() {
    return {
      allResourceList: [],
      tableData: [],
      filterText: "",
      dataCount: 0,
      pageSize: 10,
      currentPage: 1,
      libraryFileType: "Website",

      // 上传文件的模态框
      addItemModal: false,
      file: "",
      fileDescription: "",
      fileName: "",
      fileURL: "",
      fileType: "",
      addOperationType: "single",
      toUploadFiles: [],

      // 编辑文件的模态框
      editItemForm: {},
      editModal: false,

      contentHeight: "",
      panel: null,
      showModal: false,
      checkAll: false,
      checkedSymbols: [],
      isIndeterminate: false,

      currentItemNum: 0,
      searchFinished: false,
      inputSearchText: "",
      searchTag: "name",
      userInfo: {},
    };
  },
  mounted() {
    window.addEventListener("resize", this.reSize);
    this.reSize();
    this.initLayout();
    this.userInfo = JSON.parse(localStorage.getItem("userInfo"));
    // this.readResource();
    // this.readResource();
  },
  beforeDestroy: function () {
    window.removeEventListener("resize", this.reSize);
  },
  created() {},
  methods: {
    reSize() {
      let currentHeight = window.innerHeight;
      if (currentHeight > 900) {
        this.pageSize = 10;
        this.readResource();
      } else {
        this.pageSize = 6;
        this.readResource();
      }
    },
    async search() {
      this.currentPage = 1;
      if (this.inputSearchText == "") {
        this.readResource();
      } else {
        let reqInfo = {
          asc: false,
          page: 0,
          pageSize: this.pageSize,
          searchField: this.searchTag,
          searchText: this.inputSearchText,
        };
        let that = this;
        try {
          let res = await post(
            "/visualResourceLibrary/res/resource/query/" + this.libraryFileType,
            reqInfo
          );
          // console.log(res);
          let resList = res.data.data.content;
          that.dataCount = res.data.data.total;
          that.tableData = [];
          if (resList.length > 0) {
            for (let i = 0; i < resList.length; i++) {
              if (
                resList[i].type &&
                resList[i].type != null &&
                resList[i].type != undefined &&
                resList[i].type != ""
              ) {
                that.tableData.push(resList[i]);
              } else {
              }
            }
          }
          that.searchFinished = true;
        } catch (e) {
          console.log(e);
        }
      }
    },
    initLayout() {
      this.contentHeight = window.innerHeight - 200 + "px";
    },
    async readResource() {
      this.allResourceList = [];
      let reqInfo = {
        asc: false,
        page: 0,
        pageSize: this.pageSize,
      };
      let that = this;
      try {
        let res = await post("/visualResourceLibrary/res/resource/browse/0", reqInfo);
        // console.log(res);
        let resList = res.data.data.content;
        that.dataCount = res.data.data.total;
        that.tableData = [];
        if (resList.length > 0) {
          for (let i = 0; i < resList.length; i++) {
            if (
              resList[i].type &&
              resList[i].type != null &&
              resList[i].type != undefined &&
              resList[i].type != ""
            ) {
              resList[i].tempId = i + 1;
              that.tableData.push(resList[i]);
            } else {
            }
          }
        }
        that.currentItemNum = that.allResourceList.length;
        that.searchFinished = false;
        that.inputSearchText = "";
      } catch (e) {
        console.log(e);
      }
    },
    async changepage(index) {
      this.currentPage = index;

      let reqInfo = {
        asc: false,
        page: index - 1,
        pageSize: this.pageSize,
      };
      this.tableData = [];
      //判断是否为搜索情况下的翻页
      if (this.inputSearchText == "") {
        //正常的进入文件夹翻页
        let that = this;
        try {
          let res = await post("/visualResourceLibrary/res/resource/browse/0", reqInfo);
          // console.log(res);
          let resList = res.data.data.content;
          that.dataCount = res.data.data.total;
          if (resList.length > 0) {
            for (let i = 0; i < resList.length; i++) {
              if (
                resList[i].type &&
                resList[i].type != null &&
                resList[i].type != undefined &&
                resList[i].type != ""
              ) {
                resList[i].tempId = i + 1;
                that.tableData.push(resList[i]);
              } else {
              }
            }
          }
        } catch (e) {
          console.log(e);
        }
      } else {
        //搜索的翻页
        reqInfo.searchField = "name";
        reqInfo.searchText = this.inputSearchText;
        let that = this;
        try {
          let res = await post(
            "/visualResourceLibrary/res/resource/query/" + this.libraryFileType,
            reqInfo
          );
          // console.log(res);
          let resList = res.data.data.content;
          that.dataCount = res.data.data.total;
          if (resList.length > 0) {
            for (let i = 0; i < resList.length; i++) {
              if (
                resList[i].type &&
                resList[i].type != null &&
                resList[i].type != undefined &&
                resList[i].type != ""
              ) {
                resList[i].tempId = i + 1;
                that.tableData.push(resList[i]);
              } else {
              }
            }
          }
        } catch (e) {
          console.log(e);
        }
      }
    },
    addItemModalShow() {
      this.addItemModal = true;
      this.fileName = "";
      this.fileDescription = "";
      this.fileURL = "";
      this.fileType = "";
    },
    async submitFile() {
      if (this.addOperationType == "single") {
        //单条目上传
        let form = {
          name: this.fileName,
          description: this.fileDescription,
          webUrl: this.fileURL,
          webType: this.fileType,
          type: "Website",
          folderId: "0",
        };
        let formList = [];
        formList.push(form);
        try {
          let res = await post("/visualResourceLibrary/res/noFile/in", formList);
          // console.log(res);
          res.data.data[0].tempId = this.dataCount + 1;
          this.dataCount = this.dataCount + 1;
          // this.tableData.push(res.data.data[0]);
          this.readResource();
          this.$Notice.info({ title: "添加成功" });
        } catch (e) {
          console.log(e);
        }
      } else {
        //多条目上传））（待定）
      }
    },
    gatherFile(file) {
      let fileType = file.name.split(".")[1];
      if (
        this.fileType == "compressed" &&
        fileType != "zip" &&
        fileType != "rar" &&
        fileType != "7z"
      ) {
        this.$Message.warning("请上传压缩包");
        return false;
      }
      let that = this;
      if (that.toUploadFiles.length >= 10) {
        if (this.fileCountTimer != null) {
          clearTimeout(this.fileCountTimer);
        }
        this.fileCountTimer = setTimeout(() => {
          this.$Message.info("最多只能上传10个文件");
        }, 500);
      } else {
        var fileSize = file.size;
        if (fileSize < 1024) {
          file.fileSize = fileSize + "b";
        } else if (fileSize < 1024 * 1024) {
          file.fileSize = Math.round((fileSize / 1024) * 100) / 100 + "Kb";
        } else {
          file.fileSize = Math.round((fileSize / (1024 * 1024)) * 100) / 100 + "Mb";
        }
        that.toUploadFiles.push(file);
        // console.log(file);
      }
      return false;
    },
    delFileList(index) {
      this.toUploadFiles.splice(index, 1);
    },
    handleEdit(item) {
      this.editItemForm = JSON.parse(JSON.stringify(item));
      this.editModal = true;
    },
    async deleteItem() {
      let list = [];
      list.push(this.editItemForm.id);
      try {
        let res = await get("/visualResourceLibrary/res/delete/0/" + list.toString());
        console.log(res);
        // this.tableData.push(res.data.data[0]);
        this.editModal = false;
        this.readResource();
        this.$Notice.info({ title: "修改成功" });
      } catch (e) {
        console.log(e);
      }
    },
    async submitEdit() {
      try {
        let formData = new FormData();
        formData.append("resId", this.editItemForm.id);
        formData.append("name", this.editItemForm.name);
        formData.append("description", this.editItemForm.description);
        formData.append("url", this.editItemForm.url);
        let res = await post("/visualResourceLibrary/res/update", formData);
        // console.log(res);
        // this.tableData.push(res.data.data[0]);
        this.editModal = false;
        this.readResource();
        this.$Notice.info({ title: "修改成功" });
      } catch (e) {
        console.log(e);
      }
    },
    copyUrl(item) {
      // console.log(item);
      let input = document.createElement("input"); // 直接构建input
      input.value = item.url; // 设置内容 需要复制的内容
      document.body.appendChild(input); // 添加临时实例
      input.select(); // 选择实例内容
      document.execCommand("Copy"); // 执行复制
      document.body.removeChild(input); // 删除临时实例
      this.$Message.success("网址已复制到剪切板！");
    },
    enterUrl(item) {
      let target = this.$refs.target;
      target.setAttribute("href", item.url);
      target.click();
    },
  },
};
</script>

<style scoped>
.main {
  display: flex;
}
.menu_literature {
  border: 1px solid lightgray;
  min-width: 200px;
  margin-top: 20px;
  z-index: 0;
  height: fit-content;
}
.resourcePanel {
  flex: 1;
}
.literature_container {
  width: 100%;
  margin-top: 30px;
}
.target {
  width: 0%;
  height: 0%;
}
.btnPanel button {
  margin-left: 20px;
}

.ivu-table td,
.ivu-table th {
  height: 40px !important;
}
.project-input {
  margin-top: 20px;
  /*margin-bottom: 10px;*/
  /*margin-left: 4.16666667%;*/
  width: 400px;
  height: 3px;
}
.search-btn {
  margin-top: 20px;
  margin-bottom: 10px;
  margin-left: 20px;
  /* font-size: 0.5rem; */
  width: 100px;
  background-color: rgba(21, 88, 145, 0.8);
  color: rgba(255, 255, 255, 1);
}
.add-btn {
  margin-top: 20px;
  margin-bottom: 10px;
  margin-left: 20px;
  /* font-size: 0.5rem; */
  width: 110px;
}
.level_btn {
  /*margin-left: 20px;*/
  height: 50px;
}
.mask {
  background-color: transparent;
  opacity: 0.3;
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 1;
}
.pop {
  background-color: #fff;
  border: 1px solid lightgray;

  position: fixed;
  top: 70px;
  left: 300px;
  width: calc(100% - 600px);
  height: calc(100% - 100px);
  z-index: 2;
}
.btn {
  background-color: #fff;
  border-radius: 4px;
  border: 1px solid blue;
  padding: 4px 12px;
}
.input-style {
  /*margin-bottom: 10px;*/
  /*margin-left: 4.16666667%;*/
  width: 400px;
  margin-top: 10px;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 14px;
  border: 1px solid lightgray;
  color: #8c939d;
  width: 58px;
  height: 58px;
  line-height: 58px;
  text-align: center;
}
.avatar {
  width: 58px;
  height: 58px;
  display: block;
}
.form-btn {
  border: 1px solid #e0e0e0;
  background-color: unset;
  height: 30px;
  width: 50px;
  font-size: 12px;
  float: right;
  margin-right: 50px;
}
</style>
